import {
	dev_base_api,
	stage_base_api,
	prod_base_api,
} from "@/config.js";
import store from "@/store";
import _ from "lodash";
let baseUrl = '';
const accountInfo = uni.getAccountInfoSync();
if (accountInfo?.miniProgram?.envVersion === 'develop') { //开发版
	baseUrl = dev_base_api;
} else if (accountInfo?.miniProgram?.envVersion === 'trial') { //体验版
	baseUrl = stage_base_api;
} else { //正式版
	baseUrl = prod_base_api;
}

// 获取随机数
const getRadomId = () => {
	return new Date().getTime() + parseInt(String(Math.random() * 1000));
}

// 用户信息过期，退出登录
const logout = _.debounce(() => {
	uni.showModal({
		title: '提示',
		content: '登录状态已过期，请重新登录',
		showCancel: false,
		success: (res) => {
			if (res.confirm) {
				store.dispatch('logout');
				uni.reLaunch({
					url: '/pages/login/login'
				})
			}
		}
	})
}, 300)

// 验证回传信息
const checkRes = (res) => {
	if (res?.data?.error?.data?.message.indexOf('登录超时,请重新登录') > -1 || res?.data?.error?.data?.message.indexOf(
			'Session expired') > -1) {
		logout();
	} else {
		return res;
	}
}

// 请求
const http = ({
	url,
	header,
	params
}) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			timeout: 60000,
			data: {
				jsonrpc: "2.0",
				method: "call",
				params,
				id: getRadomId(),
			},
			header,
			method: 'POST',
			success: (res) => {
				resolve(checkRes(res));
			},
			fail: (err) => {
				uni.showToast({
					icon: "error",
					title: '系统错误',
				})
				reject(err);
			}
		})
	})
}

export const authenticate = (params) => {
	return http({
		url: '/web/session/authenticate',
		params,
	});
}

export const search_read = (params) => {
	const cookie = store.state.cookie || '';
	const header = {
		Cookie: cookie,
	};
	let user_context = store.state.user_context;
	user_context = JSON.parse(user_context || '{}');
	return http({
		url: '/web/dataset/search_read',
		params: {
			...params,
			user_context,
		},
		header,
	});
}

export const call_kw = (params) => {
	const cookie = store.state.cookie || '';
	const header = {
		Cookie: cookie,
	};
	let user_context = store.state.user_context;
	user_context = JSON.parse(user_context || '{}');
	return http({
		url: '/web/dataset/call_kw',
		params: {
			...params,
			user_context,
		},
		header,
	});
}